<?php
namespace app\common\model;
use think\Db;
class Token{
    
    /**
     * 创建token信息
     * @param unknown $d 字段有  'type','phone','email','code','token'
     */
    static public function create( $d = [] ){
        if(isset($d['phone']) && $d['phone']){
            Db::name('token')->where('phone',$d['phone'])->where('type',$d['type'])->delete();
        }else{
            Db::name('token')->where('email',$d['email'])->where('type',$d['type'])->delete();
        }
        
        $d['create_time'] = time();
        $id = Db::name('token')->insertGetId($d);    
        if( !$id )
            return com_error(['生成token失败!']);
        return $id;   
    }
    
    /**
     * 验证token
     * @param string $key 验证联系方式， 字段有 email, phone
     * @param string $val 验证值                 字段有 code, token 
     * @param number $type 验证类型
     */
    static public function check( $key='',  $val='', $type=0){
        switch ($type){
            case 0: #重置密码，email:code
                return self::checkEmail($key, $val);
        }   
    }
    
    /**
     * 邮箱验证码，验证
     * @param unknown $email
     * @param unknown $code
     * @return \my\false;|boolean
     */
    static public function checkEmail($email, $code){
        $rs = Db::name('token')->where('email', $email)->find();
        if(!$rs)
            return com_error(['错误的邮箱！']);
        if( $rs['code']!=$code ){
            if($rs['error_times']<3){
                Db::query("update token set error_times=error_times+1 where id=?",[$rs['id']]);
            }else{
                Db::name('token')->delete($rs['id']);
            }
            return com_error(['验证码错误!']);
        }
        Db::name('token')->delete($rs['id']);
        return true;
    }
    
}